package com.voice.server.service.impl;

import com.voice.server.entity.Role;
import com.voice.server.entity.RoleFunction;
import com.voice.server.repository.FunctionRepository;
import com.voice.server.repository.RoleFunctionRepository;
import com.voice.server.repository.RoleRepository;
import com.voice.server.repository.UserRoleRepository;
import com.voice.server.service.RoleService;
import com.wangjiacai.hqlQuery.service.impl.BaseServiceImpl;
import com.wangjiacai.hqlQuery.util.HqlUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

import java.util.List;

/*
 * @auther: wangjiacai
 *
 * @create: 2019-01-27 18:09:41
 */
@Service
public class RoleServiceImpl extends BaseServiceImpl implements RoleService {

    @Autowired
    private RoleRepository roleRepository;
    @Autowired
    private FunctionRepository functionRepository;
    @Autowired
    private RoleFunctionRepository roleFunctionRepository;
    @Autowired
    private UserRoleRepository userRoleRepository;

    @Override
    public long getRoleListNum(Role role) {
        return this.count(HqlUtil.getCountHql(role),role);
    }

    @Override
    public List<Role> getRoleList(Role role, Pageable pageable) {
        return this.find(HqlUtil.getQueryHql(role),role,pageable,Role.class);
    }

    @Override
    public void assignRoleFunctionByBhs(String functionIds, String roleId) {
        roleFunctionRepository.deleteByRoleId(roleId);
        for(String bh:functionIds.split(",")){
            String functionId=functionRepository.findFunctionIdByBh(bh);
            RoleFunction roleFunction=new RoleFunction();
            roleFunction.setFunctionId(functionId);
            roleFunction.setRoleId(roleId);
            roleFunctionRepository.save(roleFunction);
        }
    }

    @Override
    public Role addRole(Role role) {
        return roleRepository.save(role);
    }

    @Override
    public void deleteRole(String roleId) {
        userRoleRepository.deleteByRoleId(roleId);
        roleFunctionRepository.deleteByRoleId(roleId);
        roleRepository.deleteById(roleId);
    }

    @Override
    public List<Role> getAllRoleList() {
        return roleRepository.findAll();
    }
}
